//
//  UserInfoViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/30.
//  Copyright © 2020 王洋. All rights reserved.
//
#import <BRPickerView.h>
#import "UserInfoModel.h"
#import "AFNetworking.h"

#import "UserInfoRequest.h"

#import "UserInfoViewController.h"
#import "CommonTFEditViewController.h"

#import "AddressManagerViewController.h"

@interface UserInfoViewController ()<TZImagePickerControllerDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UserInfoModel *model; 
@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self request_UserInfo];
}

- (void)initView {
    
    self.title = @"个人信息";
    self.view.backgroundColor = UIColorHex(0xffffff);
    self.nickNameTF.delegate = self;
    self.wechatTF.delegate = self;
    self.nickNameTF.tag = 100;
    self.wechatTF.tag = 200;
    WEAKSELF
    self.userIcon.userInteractionEnabled = YES;
    [self.userIcon addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        [weakSelf selectPhoto];
    }];
    
    [self.sexControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        [weakSelf selSex];
    }];
    
    [self.marryDateControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        [[BA_BusinessHelper shared] callMarryCountDownViewWithType:MarryCountPlaceType_setting];
        [BA_BusinessHelper shared].BusinessHelperDismissBlock = ^(BOOL success) {
            if (success) { [weakSelf request_UserInfo];}
        };
    }];
    
    [self.homeTownControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        [self showAddressPicker];
    }];
    
    [self.addressControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        AddressManagerViewController *vc = [[AddressManagerViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    [self.personalSignatureControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
            
        CommonTFEditViewController *vc = [[CommonTFEditViewController alloc] init];
        vc.title = @"个性签名";
        vc.limitedCount = 50;
        vc.editTF.placeholder = @"快来添加个性签名吧";
        vc.placeholderStr = @"快来添加个性签名吧";
        vc.contentStr = weakSelf.model.autograph;
        vc.completion = ^(NSString * _Nonnull resultStr) {
            weakSelf.model.autograph = resultStr;
            [weakSelf request_updateUserInfo];
        };
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
    
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    switch (textField.tag) {
        case 100:{
            self.model.nickname = textField.text;
            [self request_updateUserInfo];
            
        } break;
            case 200:{
            self.model.wechatNo = textField.text;
                
                
            [self request_updateUserInfo];
                
            } break;
            
        default:
            break;
    }
    
    return YES;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.userIcon pp_clipCorners:UIRectCornerAllCorners radius:self.userIcon.frame.size.height/2];
    });
}

- (void)fillWithModel:(UserInfoModel *)model {
    
    UIImage *hold = [UIImage imageNamed:@"guide_usericon"];
    [self.userIcon sd_setImageWithURL:[NSURL URLWithString:model.imgUrl] placeholderImage:hold];
    self.nickNameTF.text = model.nickname;
    self.wechatTF.text = model.wechatNo;
    
    if (model.autograph.length > 0) {
        self.personalSignatureLab.text = model.autograph;
    }
    
    if (model.marryTime.length > 0) {
        self.marryDateLab.text = model.marryTime;
    }
    
    if (model.sex == 1) {
        self.sexLab.text = @"男";
    } else if (model.sex == 2) {
        self.sexLab.text = @"女";
    } else {
        self.sexLab.text = @"选择性别";
    }
    
}

- (void)selSex {
    
    WEAKSELF
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *liveAction = [UIAlertAction actionWithTitle:@"男"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
                                               // do destructive stuff here
        weakSelf.model.sex = 1;
        [weakSelf request_updateUserInfo];

        
    }];
    
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"女"
                                           style:UIAlertActionStyleDefault
                                         handler:^(UIAlertAction *action) {
                                             // do something here
        weakSelf.model.sex = 2;
        [weakSelf request_updateUserInfo];

    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                           style:UIAlertActionStyleCancel
                                         handler:^(UIAlertAction *action) {

    }];
    
    [alertController addAction:liveAction];
    [alertController addAction:videoAction];
    [alertController addAction:cancleAction];
    [alertController setModalPresentationStyle:UIModalPresentationPopover];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)showAddressPicker{
    
    [self.view endEditing:YES];
    
    WEAKSELF
    [BRAddressPickerView showAddressPickerWithMode:BRAddressPickerModeArea selectIndexs:@[@(10),@(6),@(7)] isAutoSelect:NO resultBlock:^(BRProvinceModel * _Nullable province, BRCityModel * _Nullable city, BRAreaModel * _Nullable area) {

        weakSelf.homeTownLab.text = [NSString stringWithFormat:@"%@%@%@",province.name,city.name,area.name];
    }];
}

- (void)selectPhoto {

    //可选择的图片数量最多为8  减去的1位多出来的加号   既然能吊起  肯定就有这么个加号

    NSInteger count = 1;
    TZImagePickerController *vc = [[TZImagePickerController alloc]
                                   initWithMaxImagesCount:count delegate:self];

    vc.naviBgColor = default_color_white;
    vc.naviTitleColor = default_color_black;
    vc.barItemTextColor = default_color_black;

    vc.photoWidth = 2048.0f;
    
    vc.preferredLanguage = @"zh-Hans";

    //筛选到只剩图片
    vc.allowPickingVideo = NO;
    vc.allowPickingMultipleVideo = NO;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;

//    vc.showSelectedIndex = YES;
    vc.showSelectBtn = NO;

    //裁剪
    vc.allowCrop = YES;
    vc.cropRect = CGRectMake( 0 ,(TTScreenHeight - TTScreenWidth)/2, TTScreenWidth, TTScreenWidth);

    WEAKSELF
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
        UIImage *images = photos.firstObject;
                        
        
        // ContentType设置
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
        manager.requestSerializer= [AFHTTPRequestSerializer serializer];
        manager.responseSerializer= [AFHTTPResponseSerializer serializer];
        [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
        
        // 上传完整地址
        NSString * urlString = [NSString stringWithFormat:@"%@headImgUpload",TT_Global_Service_Domain];
        
        [manager POST:urlString parameters:nil headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                    
            if (images != nil) {
            NSData *data = UIImageJPEGRepresentation(images, 0.2f);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            NSLog(@"%.2f",uploadProgress.fractionCompleted);

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

            if ([result isKindOfClass:[NSString class]]) {
                
                weakSelf.model.imgUrl = result;
                [weakSelf request_updateUserInfo];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }];

    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (UserInfoModel *)model {
    if (!_model) {
        _model = [[UserInfoModel alloc] init];
    }
    return _model;
}

- (void)request_UserInfo {
    WEAKSELF
    [UserInfoRequest request_userInfoComption:^(BOOL success, UserInfoModel * _Nonnull model) {
        if (success) {
            weakSelf.model = model;
            [weakSelf fillWithModel:weakSelf.model];
        }
    }];
}

- (void)request_updateUserInfo {
    NSMutableDictionary *dic = @{}.mutableCopy;
    self.model.nickname = [self disable_emoji:self.model.nickname];
    dic = [self.model modelToJSONObject];
    
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_EditMyInfo];
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [weakSelf request_UserInfo];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (NSString *)disable_emoji:(NSString *)text {

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@"*"];
    return modifiedString;
}

@end
